<template>
  <div class="info">
    <div v-if="!isShowEdit">
      <van-cell  title="头像">
        <img :lazy-load="true"  class="avatar" slot="right-icon" mode="aspectFill"
             :src="info.head_img ? picPre + info.head_img : picPre + 'front/avatar.jpg'" alt="">
      </van-cell>
      <van-cell title="电话号码" :value="info.mobile"></van-cell>
      <van-cell title="昵称" :value="info.username"></van-cell>
      <van-cell title="性别"  :value="info.sex == 1? '男': info.sex == 2 ? '女': ''"></van-cell>
      <van-cell title="所在省市" :value="info.provice_city"></van-cell>
      <van-cell title="生日" :value="info.birthday"></van-cell>
    </div>
    <div v-else>
      <van-cell  title="头像">
        <img :lazy-load="true"  class="avatar" slot="right-icon" mode="aspectFill" ﻿@tap="chooseImg"
             :src="newInfo.head_img ? picPre + newInfo.head_img : picPre + 'front/avatar.jpg'" alt="">
      </van-cell>
      <van-cell title="电话号码" :value="info.mobile"></van-cell>
      <van-field label="昵称" :value="newInfo.username" @blur="changeUserName" placeholder="请输入昵称"
                 :border="false"></van-field>
      <van-cell title="性别" ﻿@tap="showSex" is-link  :value="newInfo.sex == 1? '男': newInfo.sex == 2 ? '女': ''"></van-cell>
      <van-cell title="所在省市" is-link ﻿@tap="showArea" :value="newInfo.provice_city"></van-cell>
      <van-cell title="生日" ﻿@tap="showDate" is-link :value="newInfo.birthday"></van-cell>
    </div>

<!--    选择性别-->
    <van-popup :show="isShowSex" @close="isShowSex = false" position="bottom">
      <van-picker :columns="actions" show-toolbar
                  title="性别" @confirm="changeSex"
                  @cancel="isShowSex = false"></van-picker>
    </van-popup>
    <!--    选择省市-->
    <van-popup :show="isShowAdd" @close="isShowAdd = false" position="bottom">
      <van-area title="所在省市"  @cancel="isShowAdd = false" @confirm="changeAdd" :area-list="areaList" value="110101" :columns-num="2" ></van-area>
    </van-popup>
    <!--    选择时间-->
    <van-popup :show="isShowDate" @close="isShowDate = false" position="bottom">
      <van-datetime-picker
        type="date"
        :min-date="minDate"
        :value="currentDate"
        @confirm="changeDate"
        @cancel="isShowDate = false"
        :max-date="maxDate"
      ></van-datetime-picker>
    </van-popup>
    <div class="btn-wrapper">
      <van-button type="default" v-if="!isShowEdit" size="large" ﻿@tap="showEdit">编辑</van-button>
      <div v-else class="btn-box">
        <van-button class="cancel" ﻿@tap="isShowEdit = false" >取消</van-button>
        <van-button  ﻿@tap="editInfo" type="primary">确认修改</van-button>
      </div>
    </div>
  </div>
</template>

<script>
  import moment from 'moment'
  import areaList from '@/tool/area';
  import { getToken } from "@/tool/qiniu";
    export default {
      name: "info",
      data() {
        let that = this;
        return {
          areaList,
          picPre: that.$api.picPre,
          actions: ["男", "女"],
          isShowSex: false,
          isShowDate: false,
          isShowAdd: false,
          currentDate: '',
          info: {},
          minDate: new Date(1949,1,1).getTime(),
          newInfo: {},
          isShowEdit: false,
          maxDate: new Date().getTime(),
          loadingEnd:{
            moduleOne: false,
          },
        }
      },
      methods: {
        moment,
        goPage(url){
			uni.navigateTo({
				url: url
			})
		},
        showEdit(){
          this.newInfo = JSON.parse(JSON.stringify(this.info))
          this.isShowEdit = !this.isShowEdit
        },
        showDate(){
          if(this.isShowEdit){
            this.isShowDate = !this.isShowDate
          }
        },
        showSex(){
          if(this.isShowEdit) {
            this.isShowSex = !this.isShowSex
          }
        },
        showArea(){
          if(this.isShowEdit) {
            this.isShowAdd = !this.isShowAdd
          }
        },
        changeUserName(event){
          console.log(event.target.value)
          this.newInfo.username = event.target.value;
        },
        changeDate(data){
          this.currentDate = data.mp.detail
          this.newInfo.birthday = moment(data.mp.detail).format("YYYY-MM-DD")
          this.isShowDate = false
        },
        changeAdd(data){
          this.newInfo.city_code = data.mp.detail.values[1].code
          this.newInfo.province_code = data.mp.detail.values[0].code
          this.newInfo.provice_city = data.mp.detail.values[0].name + ' ' + data.mp.detail.values[1].name
          this.isShowAdd = false
        },
        changeSex(data){
          if(data.target.value === '男'){
            this.newInfo.sex = 1
          } else{
            this.newInfo.sex = 2
          }
          this.isShowSex = false
        },
        chooseImg: function () {
          let that = this;
          ﻿uni.chooseImage({
            count: 1, // 默认最多一次选择1张图
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              console.log(res)
              // 支持多图上传
              for (var i = 0; i < res.tempFilePaths.length; i++) {
                // 验证格式
                if (!/.(jpg|jpeg|png)$/i.test(res.tempFilePaths[i])) {
                  setTimeout(function () {
                    ﻿uni.showToast({
                      title: '图片格式有误',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 500)
                  return
                }
                if (res.tempFiles[i].size > 1024*1024) {
                  setTimeout(function () {
                    ﻿uni.showToast({
                      title: '图片应小于1M',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 500)
                  return
                }
                // 显示消息提示框
                setTimeout(function() {
                  ﻿uni.showLoading({
                    title: '上传中...',
                    mark: true
                  })
                }, 500)
                ﻿uni.uploadFile({
                  url: that.$api.uploadAvatar,
                  filePath:res.tempFilePaths[i],
                  name: "file",
                  header:{
                    Cookie : "frontend="+ ﻿uni.getStorageSync('sessionId'),
                    token: ﻿uni.getStorageSync('token')
                  },
                  success(res){
                    setTimeout(function() {
                      ﻿uni.hideLoading()
                    }, 500)
                    let result = JSON.parse(res.data)
                    if(result.data.status === 200){
                      setTimeout(function () {
                        ﻿uni.showToast({
                          title: '上传成功',
                          icon: 'none',
                          duration: 2000
                        })
                      }, 500)
                      that.newInfo.head_img = result.data.data.img_url;
                    } else {
                      setTimeout(function () {
                        ﻿uni.showToast({
                          title: result.data.msg,
                          icon: 'none',
                          duration: 2000
                        })
                      }, 500)
                    }
                  },
                  fail: function (error) {
                    setTimeout(function() {
                    ﻿uni.hideLoading()
                    }, 400)
                    setTimeout(function () {
                      ﻿uni.showToast({
                        title: '上传图片失败',
                        icon: 'none',
                        duration: 2000
                      })
                    }, 500)
                  }
                })
              }
            },
            fail: function (res) {
              setTimeout(function () {
                ﻿uni.showToast({
                  title: '选择图片失败',
                  icon: 'none',
                  duration: 2000
                })
              }, 500)
            }
          })
        },
        editInfo(){
          ﻿uni.showLoading({
            title: '请稍后',
            mask: true
          });
          setTimeout(() => {
            this.$ajax
              .post(this.$api.editMemberInfo, {
                sex: this.newInfo.sex,
                mobile: this.info.mobile,
                city_code: this.newInfo.city_code,
                province_code: this.newInfo.province_code,
                birthday: this.newInfo.birthday,
                username: this.newInfo.username,
                head_img: this.newInfo.head_img
              })
              .then(res => {
                ﻿uni.hideLoading()
                ﻿uni.showToast({
                  title: '修改成功',
                  duration: 800
                })
                this.viewLoad()
                this.isShowEdit = false
              })
              .catch(err => {
                ﻿uni.hideLoading()
                ﻿uni.showToast({
                  title: err,
                  icon: 'none',
                  duration: 2000
                })
              });
          }, 800)
        },
        getPersonInfo(){
          this.$ajax
            .post(this.$api.getMemberInfo)
            .then(res => {
              this.loadingEnd.moduleOne = true
              this.info = res
              if(res.city_id && res.province_id){
                this.info.city_code = res.city_id
                this.info.province_code = res.province_id
                this.info.provice_city = this.areaList.province_list[res.province_id] + ' ' + this.areaList.city_list[res.city_id]
              }
            })
            .catch(err => {
              this.loadingEnd.moduleOne = true
              ﻿uni.showToast({
                title: err,
                icon: 'none',
                duration: 2000
              })
            });
        },
        viewLoad(){
          this.loadingEnd = {
            moduleOne: false,
          };
          ﻿uni.showLoading({
            title: '加载中',
            mask: true
          });
          this.info = {}
          this.isShowEdit = false
          this.getPersonInfo()
        }
      },
      computed:{
        hideLoading(){
          if(this.loadingEnd.moduleOne){
            setTimeout(function(){
              ﻿uni.hideLoading()
            }, 800)
          }
        }
      },
      onLoad(){
       this.viewLoad()
      }
    }
</script>

<style scoped>
  .btn-wrapper{
    margin-top: 30rpx;
  }
  .info{
    padding: 0 30rpx;
  }
  .avatar{
    width: 98rpx;
    height: 98rpx;
    vertical-align: middle;
    border-radius: 50%;
  }
  .btn-box{
    text-align: center;
  }
  .cancel{
    margin-right: 50rpx;
  }
</style>
